const express = require('express')
const { getAll, getOne, exec } = require('../db')

var router = express.Router()

router.get('/:id', async (req, res) => {
  // 一. 解析参数
  let { id } = req.params

  let sql = `select a.*,b.type from blog_articles as a,blog_category as b where a.category_id = b.id and a.id = ${id}`

  // 二. 操作数据库
  const data = await getOne(sql)

  // 三. 返回结果
  res.send({
    code: 0,
    message: '查询成功',
    result: data,
  })
})
router.put('/:id', async (req, res) => {
  const { id } = req.params
  const { author, title, content, imgPath, type, identify, location } = req.body
  let sql = `select id from blog_category where type = '${type}'`
  const cateData = await getOne(sql)
  const categoryId = cateData.id
  sql = `update blog_articles set author ='${author}',title= '${title}',content='${content}',category_id=${categoryId},imgPath='${imgPath}',identify='${identify}',location='${location}'  where id = ${id}`
  // console.log(sql)
  const data = await exec(sql)
  // console.log(data)
  // 三. 返回结果
  res.send({
    code: 0,
    message: '修改文章成功!',
  })
})

module.exports = router
